<template>
	<view class="container">
		<!-- 横向滚动容器 -->
		<scroll-view scroll-x :scroll-left="scrollLeft" :scroll-with-animation="true" class="scroll-box" @scroll="handleScroll"
			v-if="scrollViewVisible">
			<view v-for="item in itemList" :key="item.id" class="scroll-item">
				元素 {{ item.id }}
			</view>
		</scroll-view>

		<!-- 控制按钮 -->
		<button @click="scrollToLeft">滚动到最左侧</button>
	</view>
</template>

<script setup>
	import {
		ref,
		nextTick
	} from 'vue';

	let scrollViewVisible = ref(true);
	// 响应式数据
	const scrollLeft = ref(0); // 控制横向滚动位置
	const itemList = ref(
		Array.from({
			length: 20
		}, (_, i) => ({
			id: i + 1
		}))
	);

	// 滚动事件监听
	const handleScroll = (e) => {
		console.log('当前横向滚动位置:', e.detail.scrollLeft);
	};

	// 滚动到最左侧方法
	const scrollToLeft = () => {
		scrollViewVisible.value = false;
		nextTick(() => {
			scrollViewVisible.value = true;
			scrollLeft.value = 0; // 将滚动位置重置为0（最左侧）
		})

	};
</script>

<style scoped>
	/* 容器样式 */
	.container {
		padding: 20rpx;
	}

	/* 关键：必须设置固定宽度且允许横向滚动 */
	.scroll-box {
		width: 100%;
		height: 200rpx;
		white-space: nowrap;
		/* 禁止换行 */
		border: 1px solid #eee;
	}

	/* 横向排列的子元素 */
	.scroll-item {
		display: inline-block;
		width: 150rpx;
		height: 180rpx;
		line-height: 180rpx;
		text-align: center;
		background-color: #f0f0f0;
		margin-right: 20rpx;
	}
</style>